package com.ebai.product.management.service.system;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ebai.product.management.base.cache.service.MessageCacheImpl;
import com.ebai.product.management.base.utils.SysCode;
import com.ebai.product.management.model.entity.Dict;
import com.ebai.product.management.model.entity.User;
import com.ebai.product.management.repository.system.DictRepository;

/**
 * 数据字典 业务处理类
 * @author mgli
 *
 */
@Service
public class DictService {

	@Autowired
	private DictRepository dictRepository;
	
	/**
     * 依据条件查询分页数据
     * @param page
     * @param size
     * @param authQuery
     * @return
     */
    public Page<Dict> queryPage(Integer page, Integer size, final Dict dictQuery, final String parentId) {
        Pageable pageable = PageRequest.of(page-1, size, Sort.Direction.ASC, "dataPxh");
        Page<Dict> rolePage = this.dictRepository.findAll(new Specification<Dict>(){
            public Predicate toPredicate(Root<Dict> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                
                if (StringUtils.isNotBlank(parentId)) {
                	list.add(criteriaBuilder.equal(root.get("parentId").as(String.class), parentId));
                }
                else {
                	list.add(criteriaBuilder.equal(root.get("parentId").as(String.class), SysCode.DEFAULT_USER.DICT_PARENT_ID));
                }
                
                // 过滤字典名称
                if ( StringUtils.isNotBlank(dictQuery.getDataText()) ){
                    list.add(criteriaBuilder.like(root.get("dataText").as(String.class), "%"+ dictQuery.getDataText() +"%"));
                }
                // 过滤字典类型
                if ( StringUtils.isNotBlank(dictQuery.getDataCode()) ){
                    list.add(criteriaBuilder.equal(root.get("codeType").as(String.class), "%"+ dictQuery.getDataCode() +"%"));
                }

                // 过滤创建时间条件
                if ( StringUtils.isNotBlank(dictQuery.getCreateTimeBetween()) ){
                    String[] createTime = dictQuery.getCreateTimeBetween().split(" ~ ");
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime").as(Timestamp.class), Timestamp.valueOf(createTime[0] + " 00:00:00")));
                    list.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime").as(Timestamp.class), Timestamp.valueOf(createTime[1] + " 23:59:59")));
                }
                // 过滤已删除的数据
                list.add(criteriaBuilder.equal(root.get("isDelete").as(String.class), SysCode.DICT_TYSF.NO));
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        }, pageable);

        return rolePage;
    }
    
    /**
     * 保存或更新表单数据
     * @param entity
     * @return
     */
    public Map<String, Object> saveData(Dict oldEntity, User sessionUser) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", Boolean.FALSE);

        try {
        	Dict newEntity = null;
            if (StringUtils.isBlank(oldEntity.getPid())) {
            	newEntity = new Dict();
            	BeanUtils.copyProperties(oldEntity, newEntity);
            	
            	newEntity.setIsDelete(SysCode.DICT_TYSF.NO);
            	newEntity.setCreator(sessionUser.getLoginName());
            	newEntity.setLastUpdateRegenerator(sessionUser.getLoginName());
            }
            else {
            	newEntity = this.dictRepository.findByPid(oldEntity.getPid());
            	oldEntity.setCreateTime(newEntity.getCreateTime());
            	oldEntity.setCreator(newEntity.getCreator());
                BeanUtils.copyProperties(oldEntity, newEntity);
                oldEntity.setLastUpdateRegenerator(sessionUser.getLoginName());
            }
            this.dictRepository.save(newEntity);

            result.put("success", Boolean.TRUE);
            result.put("msg", MessageCacheImpl.getMsg("Global.SaveData.Message.Success"));
        }
        catch (Exception e) {
            e.printStackTrace();
            result.put("msg", MessageCacheImpl.getMsg("Global.SaveData.Message.Failure") + e.getMessage());
        }

        return result;
    }

    /**
     * 依据主键执行逻辑删除
     * @param ids
     * @return
     */
    public Map<String, Object> dropData(String dataPid) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", Boolean.FALSE);

        try {
            if (StringUtils.isNotBlank(dataPid)) {
                Dict entity = this.dictRepository.findByPid(dataPid);
                entity.setIsDelete(SysCode.DICT_TYSF.YES);
                this.dictRepository.save(entity);
            }

            result.put("success", Boolean.TRUE);
            result.put("msg", MessageCacheImpl.getMsg("Global.DeleteData.Message.Success"));
        }
        catch (Exception e) {
            e.printStackTrace();
            result.put("msg", MessageCacheImpl.getMsg("Global.DeleteData.Message.Failure") + e.getMessage());
        }

        return result;
    }
}
